package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Autowired
    private IBlogService blogService;
    @Autowired
    private UserServiceImpl userService;
    @Autowired
    StringRedisTemplate stringRedisTemplate;

    //查询多个
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = blogService.query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            Long userId = blog.getUserId();
            extracted(userId, blog);
            isBlogLiked(blog);
        });
        return Result.ok(records);
    }

    /**
     * 查询一个
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {

        Blog blog = getById(id);
        if (blog == null){
            return Result.fail("笔记不存在");
        }
        //当前用户的图片和名称
        Long userId = blog.getUserId();
        extracted(userId, blog);
        isBlogLiked(blog);
        return Result.ok(blog);

    }

    private void extracted(Long userId, Blog blog) {
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }
    private void isBlogLiked(Blog blog) {
        //TODO:获取用户id
        Long userid = UserHolder.getUser().getId();
        if (userid == null) {
            // 用户未登录，默认未点赞
            blog.setIsLike(false);
            return;
        }
        //TODO:去Redis中判段用户是否已经点赞过 使用set集合中的isMember方法
        //TODO:优化为了制作点赞排行，使用zset
        Double member = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY +blog.getId(), userid.toString());
        blog.setIsLike(member==null?false:true);
    }

    /**
     * 修改点赞
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        //TODO:判断用户是否登录
        if (UserHolder.getUser() == null) {
            return Result.fail("请登录");
        }
        //TODO:获取用户id
        Long userid = UserHolder.getUser().getId();

        //TODO:去Redis中判段用户是否已经点赞过 使用set集合中的isMember方法
        //TODO:优化为了制作点赞排行，使用zset
//        Boolean member = stringRedisTemplate.opsForSet().isMember(BLOG_LIKED_KEY + id, userid.toString());
        Boolean member = stringRedisTemplate.opsForZSet().score(BLOG_LIKED_KEY + id, userid.toString()) != null;
        if (BooleanUtil.isFalse(member)) {
            //TODO:如果没有点过赞，则修改数据库，
            boolean update = blogService.update().setSql("liked=liked + 1").eq("id", id).update();
            if (update) {
                //TODO:将用户id放入Redis中
                stringRedisTemplate.opsForZSet().add(BLOG_LIKED_KEY + id, userid.toString(), System.currentTimeMillis());
            }
        }else {
            //TODO:如果已经点赞，则修改数据库，
            boolean update = blogService.update().setSql("liked=liked - 1").eq("id", id).update();
            if (update) {
                // TODO:如果点赞过，则点赞数-1，移除Redis中的用户id
                stringRedisTemplate.opsForZSet().remove(BLOG_LIKED_KEY+id, userid.toString());
            }
        }
        return Result.ok();

    }

    @Override
    public Result queryBlogLikes(Long id) {
        //去Redis中查询前五名
        Set<String> range = stringRedisTemplate.opsForZSet().range(BLOG_LIKED_KEY + id, 0, 4);
        //解析ids
        if (range == null || range.isEmpty()) {
            return Result.ok();
        }
        List<Long> ids = range.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", ids);
        //根据ids查询用户
        List<UserDTO> users = userService.query()
                .in("id", ids)
                .last("ORDER BY FIELD(id,"+join+")")
                .list()
                .stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);
    }

}
